package com.ecp.user.util;


import java.math.BigDecimal;

import org.apache.commons.lang.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import com.ecp.user.bean.PayResult;

public class PayResultUtil {
    public static PayResult xml2PayResult(String xml) {
        PayResult payResult;
        try {
            Document doc = DocumentHelper.parseText(xml);
            Element root = doc.getRootElement();
            Element head = root.element("messageHead");
            Element body = root.element("messageBody");

            int id = 0;
            String loginId;
            String orderAliasCode;
            String src;
            double shopDeposit = 0D;
            double geRenDeposit = 0D;
            int paySuccess = 0;
            String error;

            if (StringUtils.isNotEmpty(head.elementTextTrim("id"))) {
                id = new BigDecimal(head.elementTextTrim("id")).intValue();
            }
            loginId = head.elementTextTrim("loginId");
            orderAliasCode = head.elementText("orderAliasCode");
            src = head.elementTextTrim("src");
            if (StringUtils.isNotEmpty(head.elementTextTrim("shopDeposit"))) {
                shopDeposit = new BigDecimal(head.elementTextTrim("shopDeposit")).doubleValue();
            }
            if (StringUtils.isNotEmpty(head.elementTextTrim("geRenDeposit"))) {
                geRenDeposit = new BigDecimal(head.elementTextTrim("geRenDeposit")).doubleValue();
            }
            if (StringUtils.isNotEmpty(body.elementTextTrim("paySuccess"))) {
                paySuccess = new BigDecimal(body.elementTextTrim("paySuccess")).intValue();
            }
            error = body.elementTextTrim("error");

            payResult = new PayResult();
            payResult.setOrderAliasCode(orderAliasCode);
            payResult.setId(id);
            payResult.setLoginId(loginId);
            payResult.setSrc(src);
            payResult.setError(error);
            payResult.setGeRenDeposit(geRenDeposit);
            payResult.setShopDeposit(shopDeposit);
            payResult.setPaySuccess(paySuccess);
        } catch (DocumentException e) {
            e.printStackTrace();
            payResult = null;
        }
        return payResult;
    }
}
